package com.xyyl.patient.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.WxPayBaseRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.service.WxPayService;
import com.xyyl.patient.core.constant.AppEnum;
import com.xyyl.patient.core.controller.BaseController;
import com.xyyl.patient.core.util.DateUtils;
import com.xyyl.patient.core.util.ResponseBodyResult;
import com.xyyl.patient.entity.user.RechargeOrder;
import com.xyyl.patient.service.user.RechargeOrderService;

/**
 * @projectName:xyyl-patient-web
 * @ClassName: RechargeOrderPayController
 * @Description: 微信充值订单Controller
 * @author chens
 * @date 2017年8月22日
 */
@RestController
@RequestMapping("/rechargeOrderPay")
public class RechargeOrderPayController extends BaseController {

	private Logger logger = LogManager.getLogger(RechargeOrderPayController.class);

	@Autowired
	private RechargeOrderService rechargeOrderService;

	@Autowired
	private WxPayService payService;

	@Value("#{weixin['common.domain']}")
	private String domain;

	/**
	 * @Title: submitOrder @Description: 充值提交订单 1.调用微信统一下单，返回JSSDKPayInfo相关的信息
	 * 2.保存充值记录 @param @ @return String 返回类型 @throws
	 */
	@RequestMapping(value = "/submitOrder", method = RequestMethod.POST)
	public JSONObject submitOrder(@RequestBody RechargeOrder rechargeOrder) {

		logger.info("---submit  payOrder---");

		try {

			/** TODO:生成唯一订单编号,后期按指定格式生成 **/
			String preCode = DateUtils.formatDatetime(new Date(), "yyyyMMddHHss") + RandomUtils.nextInt(99999);
			String totalFee = "";
			BigDecimal rechargeAmount = rechargeOrder.getRechargeAmount();
			if (rechargeOrder != null) {
				totalFee = rechargeAmount.setScale(2).toString();
			}

			/** 组装参数信息 **/
			WxPayUnifiedOrderRequest prepayInfo = WxPayUnifiedOrderRequest.newBuilder()
					.openid(rechargeOrder.getOpenid()).outTradeNo(preCode)
					.totalFee(WxPayBaseRequest.yuanToFee(totalFee)).body(rechargeOrder.getProductName())
					.spbillCreateIp("192.168.0.1").notifyURL(domain + "/rechargeOrderPay/orderPayCallback").build();

			/** 提交微信统一下单 **/
			Map<String, String> payInfos = this.payService.getPayInfo(prepayInfo);

			if (payInfos != null && payInfos.get("package") != null) {
				rechargeOrder.setOrdersn(preCode);
				rechargeOrderService.saveRechargeOrder(rechargeOrder);
			}
			return ResponseBodyResult.success("订单提交成功!", payInfos);
		} catch (Exception e) {

			return ResponseBodyResult.error("订单提交失败!", e);
		}
	}

	/**
	 * @Title: orderPayCallback
	 * @Description: 微信通知充值结果的回调地址 1.更新订单信息 2.保存流水信息
	 * @param rechargeOrder
	 * @param
	 * @return String 返回类型 @throws
	 */
	@RequestMapping(value = "/orderPayCallback", method = RequestMethod.POST)
	public String orderPayCallback(HttpServletRequest request, HttpServletResponse response) {

		logger.info("---callback  payOrder---");

		try {
			synchronized (this) {
				/** 解析支付结果 **/
				String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
				WxPayOrderNotifyResult result = payService.parseOrderNotifyResult(xmlResult);
				if (AppEnum.common.Pay_result_success.getName().equals(result.getReturnCode())) {
					if (AppEnum.common.Pay_result_success.getName().equals(result.getResultCode())) {

						/** 支付成功，处理业务数据 **/
						String orderId = result.getOutTradeNo();
						String ordersn = result.getTransactionId();
						String openid = result.getOpenid();
						RechargeOrder rechargeOrder = rechargeOrderService.queryOrderDetail(orderId, openid);
						if (rechargeOrder.getStatus().equals(AppEnum.common.Recharge_status_not.getValue())) {
							rechargeOrder.setStatus(AppEnum.common.Recharge_status_finish.getValue());
							rechargeOrder.setPayOrdersn(ordersn);
							rechargeOrder.setPaytime(DateUtils.currentDatetime());
							rechargeOrderService.confirmPay(rechargeOrder);
						}

						return WxPayNotifyResponse.success("ok");
					} else {
						return WxPayNotifyResponse.fail("result_code is FAIL");
					}
				} else {
					return WxPayNotifyResponse.fail("check signature FAIL");
				}

			}
		} catch (Exception e) {
			return WxPayNotifyResponse.fail("http request FAIL");
		}

	}

}
